﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BSPTree
{
    class BSPTree
    {
        BSPNode root;
        List<BSPNode> leafList;


        public BSPTree()
        {
            leafList = new List<BSPNode>();
            root = new BSPNode(null);
            //subscribe to the event so the tree knows when a new node is created
            root.NodeCreated += AddNewLeaf;
            //need to prime the list with root
            leafList.Add(root);
        }

        public void AddNewLeaf(BSPNode newNode)
        {
            //by definition a new node is going to be a leaf
            leafList.Add(newNode);
        }

        public void SplitLeafs()
        {
            //we can't read off of and change the leafList at the same time
            //so we'll read off oldList and change leafList
            List<BSPNode> oldList = leafList;
            //cannot use clear!  need to leave the old version alone!
            leafList = new List<BSPNode>();
            foreach (BSPNode curNode in oldList)
            {
                curNode.SplitNode();
            }
        }

        public void LeafReport()
        {
            foreach (BSPNode curNode in leafList)
            {
                curNode.Report();
            }
        }

        public void VisitAll()
        {
            VistNode(root);
        }

        void VistNode(BSPNode curNode)
        {
            if (curNode.children[0] != null)
            {
                VistNode(curNode.children[0]);
                VistNode(curNode.children[1]);
            }
            curNode.Report();
        }
    }
}
